home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_06_04 / v6n4016a.txt < prev    next >
Text File  |  1989-09-26  |  2KB  |  88 lines

  1.  
  2.  
  3. struct 
  4.     {
  5.     int total;
  6.     char date[9];
  7.     } customer_header;
  8.  
  9. struct 
  10.     {
  11.     int code;
  12.     char name[41];
  13.     char address[2][41];
  14.     } customer_record;
  15.  
  16. #include <stdio.h>
  17.  
  18. /* Misc. data */
  19.  
  20. FILE *customer_file;
  21.  
  22. int open_customer()
  23.     { 
  24.     /* Open as read/write */ 
  25.     if ((customer_file = fopen("customer.dat", "r++")) == NULL)
  26.         {
  27.         /* Does not exist, try creating it */  
  28.         if ((customer_file = fopen("customer.dat", "w++")) == NULL)
  29.             {
  30.             printf("Can't open customer.dat, error %d.\n", errno);
  31.             exit(errno);
  32.             }
  33.         /* Write out a initial header record */
  34.         memset(&customer_header, 0, sizeof (customer_header));
  35.         write_customer_header();
  36.         }
  37.     else 
  38.         /* Read the header record */
  39.         fread(&customer_header, sizeof (customer_header), 1, customer_file);
  40.     }
  41.  
  42.  
  43. /* Write the header record */
  44.  
  45. int write_customer_header()
  46.     {
  47.     fseek(customer_file, 0L, 0);
  48.     return fwrite(&customer_header, sizeof (customer_header), 1,
  49.         customer_file);
  50.     }
  51.  
  52. /* Read record */
  53.  
  54. int read_customer(record)
  55. int record;
  56.     {
  57.     fseek(customer_file, (long) record * sizeof (customer_record) 
  58.         + sizeof (customer_header), 0);
  59.     return fread(&customer_record, sizeof (customer_record), 1,
  60.         customer_file);
  61.     }
  62.  
  63. /* Write record */
  64.  
  65. int write_customer(record)
  66. int record;
  67.     {
  68.     fseek(customer_file, (long) record * sizeof (customer_record) 
  69.         + sizeof (customer_header), 0);
  70.     return fwrite(&customer_record, sizeof (customer_record), 1,
  71.         customer_file);
  72.     }
  73.  
  74. /* Delete a record  (slow method ) */
  75.  
  76. int delete_customer(record)
  77. int record;
  78.     {
  79.     int i;
  80.     for (i = record;  i < customer_header.total - 1;  i++)
  81.         {
  82.         read_customer(i + 1);
  83.         write_customer(i);
  84.         }
  85.     customer_header.total--;
  86.     write_customer_header();
  87.     }
  88.